﻿using FTBS.Models.BLO;
using FTBS.Models.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FTBS.Controllers
{
    public class RoleController : Controller
    {
        RoleBLO _roleBLO = new RoleBLO();

        public ActionResult Index()
        {
            return View(_roleBLO.LoadAllRoles());
        }

        //--------------Create--------------------------
        public ActionResult Create()
        {
            this.Session["RoleName"] = null;
            return View();
        }

        [HttpPost]
        public ActionResult Create(Role role)
        {
            if (ModelState.IsValid)
            {
                if (!_roleBLO.CheckIsExisted(role))
                {
                    this.Session["RoleName"] = null;
                    _roleBLO.AddRole(role);
                    return RedirectToAction("Index");
                }
                this.Session["RoleName"] = null;
                return View(role);
            }
            return View(role);
        }
        //------------Edit------------------------------
        public ActionResult Edit(int roleId = 0)
        {
            Role role = _roleBLO.LoadARole(roleId);
            if (role == null)
            {
                return HttpNotFound();
            }
            this.Session["curName"] = role.RoleName;
            this.Session["RoleName"] = null;
            return View(role);

        }
        [HttpPost]
        public ActionResult Edit(Role role)
        {
            if (ModelState.IsValid)
            {
                int compare = String.Compare(role.RoleName, (String)this.Session["curName"]);
                if (!_roleBLO.CheckIsExisted(role) || (_roleBLO.CheckIsExisted(role) && compare == 0))
                {
                    this.Session["RoleName"] = null;
                    _roleBLO.UpdateRole(role);
                    return RedirectToAction("Index");
                }
                else if (_roleBLO.CheckIsExisted(role) && compare != 0)
                {
                    this.Session["RoleName"] = role.RoleName;
                    return View(role);
                }
            }
            return View(role);
        }
        //------------------Delete---------------------
        [HttpDelete, ActionName("Delete")]
        public ActionResult Delete(int id = 0)
        {
            Role role = _roleBLO.LoadARole(id);
            if (role == null)
            {
                return HttpNotFound();
            }
            _roleBLO.DeleteRole(role);
            return RedirectToAction("Index");
        }

    }
}
